<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 15:28
 */

namespace app\modules\api\controllers\open;

use app\modules\api\controllers\Controller;
use app\modules\api\models\CatListForm;
use app\modules\api\models\GoodsForm;
use app\modules\api\models\IndexForm;
use app\modules\api\models\GoodsListForm;
use app\modules\api\models\CatForm;
use app\opening\BaseApiResponse;
use app\models\Cat;
use app\models\Goods;
use app\models\Attr;
use app\models\AttrGroup;
use app\models\GoodsCat;
use app\models\GoodsUpLogs;
use app\modules\mch\models\LevelListForm;
use app\models\PrinceGoodsRelation;//P_ADD
use app\models\PrinceConfig;//P_ADD
use app\models\GoodsPic;
use app\opening\Serializer;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;

class GoodsController extends BaseController
{

    public $store_id;

    /**
     * 首页接口
     */
    public function actionIndex()
    {
        $form            = new IndexForm();
        $form->store_id  = $this->store->id;
        $form->_platform = \Yii::$app->request->get('_platform');
        $form->page_id   = \Yii::$app->request->get('page_id');
        return $form->search();
    }

    /**
     * 商品分类开表
     * @return \app\opening\ApiResponse|mixed
     * author eRic
     * dateTime 2019-08-04 9:56
     */
    public function actionCatList()
    {
        $form             = new CatListForm();
        $form->attributes = \Yii::$app->request->get();
        $form->store_id   = $this->store->id;
        return $form->search();
    }

    /**
     * 商品列表
     * @return \app\opening\ApiResponse
     * author eRic
     * dateTime 2019-08-04 9:49
     *
     */
    public function actionList()
    {
        $form             = new GoodsListForm();
        $form->attributes = \Yii::$app->request->get();
        $form->store_id   = $this->store->id;
        $form->date_start = \Yii::$app->request->get('date_start');
        $form->date_end   = \Yii::$app->request->get('date_end');
        $form->page       = \Yii::$app->request->get('page');
        $form->limit      = \Yii::$app->request->get('limit');
        return $form->searchOpen(\Yii::$app->request->get('status'));
    }

    /**
     * 商品详情
     * author eRic
     * dateTime 2019-08-04 9:50
     */
    public function actionDetail()
    {
        $form             = new GoodsForm();
        $form->attributes = \Yii::$app->request->get();
        $form->store_id   = $this->store->id;
        return $form->searchOpen();
    }

    /**
     * 创建商品分类
     * author eRic
     * dateTime 2019-08-05 9:43
     */
    public function actionAddCat()
    {
        $cat  = new Cat();
        $form = new CatForm();
        if (\Yii::$app->request->isPost) {
            $model                = \Yii::$app->request->post();
            $model['pic_url']     = '';
            $model['big_pic_url'] = '';
            $model['advert_pic']  = '';
            $model['advert_url']  = '';
            $model['store_id']    = $this->store->id;
            $form->attributes     = $model;
            $form->cat            = $cat;
            return new BaseApiResponse($form->save());
        }
        return new BaseApiResponse([
            'code' => 1,
            'msg'  => '请求错误(NOT IS POST)',
            'data' => [],
        ]);
    }

    /**
     * 创建商品分类
     * author eRic
     * dateTime 2019-08-05 9:43
     */
    public function addCat($name, $store_id)
    {
        $catInfo = Cat::findOne([
            'name'      => $name,
            'store_id'  => $store_id,
            'is_delete' => 0
        ]);
        if (!$catInfo) {
            $cat                  = new Cat();
            $form                 = new CatForm();
            $model['name']        = $name;
            $model['sort']        = 100;
            $model['parent_id']   = 0;
            $model['is_show']     = 1;
            $model['pic_url']     = '';
            $model['big_pic_url'] = '';
            $model['advert_pic']  = '';
            $model['advert_url']  = '';
            $model['store_id']    = $store_id;
            $form->attributes     = $model;
            $form->cat            = $cat;
            $result               = $form->save();
            if ($result['code'] == 0) {
                return $result['data']['cat_id'];
            }
            return false;
        }
        return $catInfo->id;
    }


    /**
     * 上传发布商品
     * author eRic
     * dateTime 2019-08-05 9:45
     */
    public function actionUpGoods()
    {
        $goods     = new Goods();
        $levelForm = new LevelListForm();
        $levelList = $levelForm->getAllLevel();

        if (\Yii::$app->request->isPost) {

            $model = \Yii::$app->request->post();
            //加入日志
            $GoodsUpLogs = new GoodsUpLogs();
            $GoodsUpLogs->source_name = $model['source_name'];
            $GoodsUpLogs->source_goods_id = $model['source_goods_id'];
            $GoodsUpLogs->request_data = serialize($model);
            if(isset($_SERVER['REMOTE_ADDR'])){
                $GoodsUpLogs->source_ip = $_SERVER['REMOTE_ADDR'];
            }
            $GoodsUpLogs->save();

            if ($model['quick_purchase'] == 0) {
                $model['hot_cakes'] = 0;
            }
            // 验证数据
            $postValidator = $this->goodsValidator($model);
            // 开启事务
            $t = \Yii::$app->db->beginTransaction();
            if (isset($postValidator['code']) && $postValidator['code'] == 0) {
                return new BaseApiResponse($postValidator);
            }

            $this->store_id = $model['store_id'];
            $cat_id         = $this->addCat($model['cat_name'], $model['store_id']);
            if (!$cat_id) {
                $t->rollBack();
                return new BaseApiResponse([
                    'code' => 1,
                    'msg'  => '商品上传失败（商品分类创建未成功）',
                    'data' => [],
                ]);
            }
            $model['cat_id'] = $cat_id;
            unset($model['cat_name']);
            $model['mch_id'] = 0;

            // 规格的处理
            list($default_attr, $default_attr_group) = Goods::getDefaultAttr($this->store_id);
            $attr       = [
                [
                    'attr_list' => [
                        [
                            'attr_group_name' => $default_attr_group->attr_group_name,
                            'attr_id'         => $default_attr->id,
                            'attr_name'       => $default_attr->attr_name,
                        ],
                    ],
                    'num'       => intval($model['goods_num']) ? intval($model['goods_num']) : 0,
                    'price'     => $model['price'],
                    'no'        => ''
                ],
            ];
            $goods_attr = \Yii::$app->serializer->encode($attr);
            if ($model['use_attr'] && !empty($model['attr'])) {
                $resultsk = $this->AttrValidator($model['attr']);
                if (isset($resultsk['code']) && $resultsk['code'] == 0) {
                    return new BaseApiResponse($resultsk);
                }
                $goods_attr = $this->saveAttr($model['attr']);
            }
            $model['attr'] = $goods_attr;


            $model['full_cut'] = \Yii::$app->serializer->encode([
                'pieces'   => '',   // 单品满件包邮
                'forehead' => '' // 单品满额包邮
            ]);
            $model['integral'] = \Yii::$app->serializer->encode([
                'give'     => 0,   // 积分增送
                'forehead' => 0, // 积分抵扣
                'more'     => ''
            ]);
            $pics              = $model['pics'];
            unset($model['pics']);
            $goods->attributes      = $model;
            $goods->addtime         = time();
            $goods->update_time     = time();
            $goods->source_name     = $model['source_name'];
            $goods->source_goods_id = $model['source_goods_id'];
            $goods->service          = $model['server'];
            $goods->goods_num       = $model['goods_num'];
            if ($goods->save()) {
                //商品图片保存
                if (!empty($pics)) {
                    $pics = (array)\Yii::$app->serializer->decode($pics);
                    if (is_array($pics) && count($pics)) {
                        foreach ($pics as $pic_url) {
                            $goods_pic            = new GoodsPic();
                            $goods_pic->goods_id  = $goods->id;
                            $goods_pic->pic_url   = $pic_url;
                            $goods_pic->is_delete = 0;
                            $goods_pic->save();
                        }
                    }
                }

                //
                if($cat_id){
                    $cat = new GoodsCat();
                    $cat->goods_id = $goods->id;
                    $cat->store_id = $goods->store_id;
                    $cat->addtime = time();
                    $cat->cat_id = $cat_id;
                    $cat->is_delete = 0;
                    $cat->save();
                }

                //更新就日志
                $GoodsUpLogs->goods_id = $goods->id;
                $GoodsUpLogs->status = 1;
                $GoodsUpLogs->save();
                $t->commit();
                return new BaseApiResponse([
                    'code' => 0,
                    'msg'  => '商品上传成功',
                    'data' => ['goods_id' => $goods->id],
                ]);
            };


            $t->rollBack();
            return new BaseApiResponse([
                'code' => 1,
                'msg'  => '商品上传失败',
                'data' => [],
            ]);
        }

        return new BaseApiResponse([
            'code' => 1,
            'msg'  => '请求错误(NOT IS POST)',
            'data' => [],
        ]);
    }

    /**
     * 处理商品规格
     * @param $attrJson
     * author eRic
     * dateTime 2019-08-07 15:14
     */
    public function saveAttr($attrJson)
    {
        $post_attr = (array)\Yii::$app->serializer->decode($attrJson);
        foreach ($post_attr as $i => &$item) {
            foreach ($item['attr_list'] as $ii => $a) {
                $attr_group_model = AttrGroup::findOne(['store_id' => $this->store_id, 'attr_group_name' => $a['attr_group_name'], 'is_delete' => 0]);
                if (!$attr_group_model) {
                    $attr_group_model                  = new AttrGroup();
                    $attr_group_model->attr_group_name = $a['attr_group_name'];
                    $attr_group_model->store_id        = $this->store_id;
                    $attr_group_model->is_delete       = 0;
                    $attr_group_model->save();
                }
                $attr_model = Attr::findOne(['attr_group_id' => $attr_group_model->id, 'attr_name' => $a['attr_name'], 'is_delete' => 0]);
                if (!$attr_model) {
                    $attr_model                = new Attr();
                    $attr_model->attr_name     = $a['attr_name'];
                    $attr_model->attr_group_id = $attr_group_model->id;
                    $attr_model->is_delete     = 0;
                    $attr_model->save();
                }
                $item['attr_list'][$ii] = [
                    'attr_group_name' => $attr_group_model->attr_group_name,
                    'attr_id'         => $attr_model->id,
                    'attr_name'       => $attr_model->attr_name,
                ];
            }
        }

        return \Yii::$app->serializer->encode($post_attr);
    }

    /**
     * 验证商品上传的数据
     * @param $model
     * @return array|bool
     * author eRic
     * dateTime 2019-08-07 16:23
     */
    public function goodsValidator($model)
    {
        if (!isset($model['cat_name']) || empty($model['cat_name'])) {
            return [
                'code' => 0,
                'msg'  => '商品类目名称不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['name']) || empty($model['name'])) {
            return [
                'code' => 0,
                'msg'  => '商品名称不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['store_id']) || empty($model['store_id']) || !is_numeric($model['store_id'])) {
            return [
                'code' => 0,
                'msg'  => '商城ID只能是数值',
                'data' => []
            ];
        }
        if (!isset($model['price']) || empty($model['price']) || !preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $model['price'])) {
            return [
                'code' => 0,
                'msg'  => '商品销售价格只能是数值,最多保留小数点2位',
                'data' => []
            ];
        }
        if ($model['price'] > 99999999.99) {
            return [
                'code' => 0,
                'msg'  => '商品售价超过限制',
                'data' => []
            ];
        }
        if (!isset($model['original_price']) || empty($model['original_price']) || !preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $model['original_price'])) {
            return [
                'code' => 0,
                'msg'  => '商品原价格只能是数值,最多保留小数点2位',
                'data' => []
            ];
        }
        if (!isset($model['goods_num']) || empty($model['goods_num']) || !is_numeric($model['goods_num'])) {
            return [
                'code' => 0,
                'msg'  => '商品库存只能是数值',
                'data' => []
            ];
        }
        if (!isset($model['detail']) || empty($model['detail'])) {
            return [
                'code' => 0,
                'msg'  => '商品详情不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['cover_pic']) || empty($model['cover_pic'])) {
            return [
                'code' => 0,
                'msg'  => '商品缩略图不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['use_attr']) || !is_numeric($model['use_attr'])) {
            return [
                'code' => 0,
                'msg'  => '是否使用规格 不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['source_name']) || empty($model['source_name'])) {
            return [
                'code' => 0,
                'msg'  => '来源名称 不能为空!',
                'data' => []
            ];
        }
        if (!isset($model['source_goods_id']) || empty($model['source_goods_id'])) {
            return [
                'code' => 0,
                'msg'  => '来源商品ID 不能为空!',
                'data' => []
            ];
        }

        return true;
    }

    /**
     * 验证规格 格式
     * @param $attrJson
     * author eRic
     * dateTime 2019-08-07 15:28
     */
    public function AttrValidator($attrJson)
    {
        $post_attr = \Yii::$app->serializer->decode($attrJson);
        $min       = 0;
        $max       = 999999;
        foreach ($post_attr as $i => $value) {
            if (!isset($value['attr_group_name']) || empty($value['attr_group_name'])) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格 组名不能为空(attr_group_name)',
                    'data' => []
                ];
            }
            if (!isset($value['attr_name']) || empty($value['attr_name'])) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格 规格名称不能为空(attr_name)',
                    'data' => []
                ];
            }
            if (floatval($value['price']) < $min) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格价格必须不小于0',
                    'data' => []
                ];
            } elseif (floatval($value['price']) > $max) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格价格必须不大于999999',
                    'data' => []
                ];
            }
            if (floatval($value['num']) < $min) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格库存必须不小于0',
                    'data' => []
                ];
            } elseif (floatval($value['num']) > $max) {
                return [
                    'code' => 0,
                    'msg'  => '商品规格库存必须不大于999999',
                    'data' => []
                ];
            }
        }
        return true;
    }
}
